import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;


public class TokenJwtManager {

    // 设置token时间
    private int tokenEcpiration = 24*60*60*1000; // 毫秒   24h

    // 编码密钥
    private String tokenSignKey = "123456";

    // 1、根据用户名生成token
    public String createToken(String userName){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, tokenEcpiration);

        String userName1 = JWT.create()
                .withHeader(new HashMap<>())
                .withClaim("userName", userName)
                .withExpiresAt(calendar.getTime()) // 过期时间
                .sign(Algorithm.HMAC256(tokenSignKey));// 签名
        return userName1;
    }

    // 2、根据token得到用户名信息
    public String getUserName(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(tokenSignKey)).build();
        DecodedJWT verify = build.verify(token);
        Claim userName = verify.getClaim("userName");
        return userName.asString();
    }

    public static void main(String[] args) {
        String ss = new TokenJwtManager().createToken("bunana3");
        System.out.println(ss);
        System.out.println(new TokenJwtManager().getUserName(ss));
    }
}
